using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace LowLevelGraphics.ImageAcquiring
{
    /// <summary>
    /// 
    /// </summary>
	public class ZooomrOnlineSearchProvider : OnlineSearchProvider
	{
		public event EventHandler FileDownloaded;
        
        /// <summary>
        /// Initializes a new instance of the <see cref="ZooomrOnlineSearchProvider"/> class.
        /// </summary>
		public ZooomrOnlineSearchProvider()
		{
			this.Host = "http://picsearch.com";
		}

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
		public override string ToString()
		{
			return "Zooomr.com";
		}

        /// <summary>
        /// Downloads the files.
        /// </summary>
        /// <param name="_sSearch">The _s search.</param>
		public override void DownloadFiles(object _sSearch)
		{
			DownloadFiles(_sSearch.ToString(), true);
		}

        /// <summary>
        /// Downloads the files.
        /// </summary>
        /// <param name="_sSearch">The _s search.</param>
        /// <param name="_bUseWebClient">if set to <c>true</c> [_b use web client].</param>
		public override void DownloadFiles(string _sSearch, bool _bUseWebClient)
		{
			string sText = string.Empty;

			if (_bUseWebClient)
			{
				WebClient client = new WebClient();

				string sDownloadString = "http://" + this.Host + "/images?hl=de&q=" + _sSearch;
				sText = client.DownloadString(sDownloadString);
			}
			else
			{
				sText = GetSocketData(this.Host, "/images?um=1&hl=de&client=firefox-a&rls=org.mozilla%3Ade%3Aofficial&q=" + _sSearch + "&btnG=Bilder-Suche", this.Host);
			}

			int nX = 0;
			int nY = 0; string[] saLink = Regex.Split(sText, "Klicken Sie um Bilddetails zu sehen");
			for (int i = 1; i < saLink.Length; i++)
			{
				try
				{
					saLink[i] = saLink[i].Replace("/imgres?imgurl=", "");
					string[] saPic = Regex.Split(saLink[i], "&imgrefurl=");
					saPic[0] = saPic[0].Replace("(", "").Replace("\"", "");

					Console.WriteLine("Pic " + i.ToString() + ": " + saPic[0]);
					HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(saPic[0]);
					HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

					Stream stream = webResponse.GetResponseStream();
					if (FileDownloaded != null)
					{
						FileDownloaded(stream, new EventArgs());
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.ToString());
				}
			}
		}
	}
}
